# -*- coding: utf-8 -*-
import os
import subprocess
import sys
import winreg
import pandas as pd
from PyQt6.QtWidgets import QApplication, QMainWindow, QFileDialog
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
from Batch_Submission_ui import Ui_Batch_Submission_Win


class PIliangtijiao(Ui_Batch_Submission_Win, QMainWindow):
    def __init__(self):
        super(PIliangtijiao, self).__init__()
        self.setupUi(self)
        self.__ui__()
        self.process_thread = None
    def __ui__(self):
        # 获取当前文件所在的文件夹路径
        self.current_folder = os.path.dirname(os.path.abspath(__file__))
        print(self.current_folder)
        os.environ['PYTHONPATH'] = os.path.join(self.current_folder,"CheckType")
        print(self.current_folder)
        self.combobox()
        self.pushButton.clicked.connect(self.select_folder)
        self.pushButton_3.clicked.connect(self.start_processing)
        self.MayaVersion.currentIndexChanged.connect(lambda *args: self.get_selected_option())

    def combobox(self):
        items = (list(self.Set_MayaVersion().keys()))
        self.MayaVersion.addItems(items)

    def get_selected_option(self):
        selected_option = self.MayaVersion.currentText()
        return(selected_option)

    def start_processing(self):
        file_list = []
        self.progressBar.setValue(0)
        file_count = self.Flie_listWidget.count()
        self.progressBar.setMaximum(file_count)

        for i in range(self.Flie_listWidget.count()):
            item = self.Flie_listWidget.item(i)
            file_list.append(item.text())
            batch_CheckPy = os.path.join(self.current_folder, "batch_Check.py")
            batch_CheckPy =batch_CheckPy.replace("\\", "/")
            cmd = self.Set_MayaVersion().get(self.get_selected_option()) +" -command \"python(\\\"execfile('"+ batch_CheckPy + "')\\\")\"  -file {}".format(item.text())
            proc = subprocess.Popen(cmd)#, creationflags=subprocess.CREATE_NO_WINDOW, stdout=subprocess.DEVNULL
            proc.wait()


        logPath = os.path.join(self.lineEdit.text(), "log")
        TxT_Log_Name = "log.txt"
        xlsx_Log_Name = "log.xlsx"
        TxT_Log = os.path.join(logPath, TxT_Log_Name)
        xlsx_Log = os.path.join(logPath, xlsx_Log_Name )
        file_name, file_extension = os.path.splitext(TxT_Log)
        if file_extension == ".txt":
            # 读取文本文件
            with open(TxT_Log, 'r', encoding='utf-8', errors='ignore') as file:
                lines = file.readlines()
            # 拆分字段并创建 DataFrame
            data = []
            for line in lines:
                parts = line.strip().split(',')
                data.append(parts)
            max_length = max(len(row) for row in data)
            columns = []
            for i in range(1, max_length + 1):
                columns.append("Column" + str(i))
            # 创建 DataFrame
            df = pd.DataFrame(data, columns=columns)
            # 创建 Excel writer 对象
            with pd.ExcelWriter(xlsx_Log, engine='openpyxl') as writer:
                # 将数据写入 Excel 表格
                df.to_excel(writer, index=False, sheet_name='Sheet1')

        # 读取 Excel 文件
        wb = load_workbook(xlsx_Log)
        # 选择工作表
        ws = wb['Sheet1']
        # 设置单元格样式
        green_fill = PatternFill(fill_type='solid', fgColor='00FF00')
        red_fill = PatternFill(fill_type='solid', fgColor='FF0000')
        # 遍历单元格并设置颜色
        for row in ws.iter_rows():
            for cell in row:
                if cell.value and 'OK' in str(cell.value):
                    cell.fill = green_fill
                if cell.value and 'NO' in str(cell.value):
                    cell.fill = red_fill
        # 保存修改
        wb.save(xlsx_Log)

    def select_folder(self):

        folder_path = QFileDialog.getExistingDirectory(self, "选择文件夹")
        print("选择的文件夹路径:", folder_path)
        self.lineEdit.setText(folder_path)
        self.Flie_listWidget.clear()
        file_type = ['ma', 'mb']
        for file_name in os.listdir(folder_path):
            # 过滤文件夹，只添加文件
            if os.path.isfile(os.path.join(folder_path, file_name)):
                file_path = os.path.join(folder_path, file_name)
                file_path = file_path.replace('\\', '/')
                if file_path.rsplit('.', 1)[-1] in file_type:
                    # 将文件名添加到列表控件
                    self.Flie_listWidget.addItem(file_path)

    def Set_MayaVersion(self):
        my_maya = {}
        for i in range(2008, 2025):
            try:
                key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,'SOFTWARE\\Autodesk\\Maya' + '\\' + str(i) + '\\' + 'Setup\\InstallPath')
                path = winreg.QueryValueEx(key, 'MAYA_INSTALL_LOCATION')
                if path[0]:
                    mayabatch = os.path.join(os.path.join(path[0], "bin"), "mayabatch.exe")
                    my_maya[str(i)] = mayabatch.replace('\\', '/')
            except:
                pass
        return (my_maya)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = PIliangtijiao()
    window.show()
    sys.exit(app.exec())
